package com.zhentao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.file.service.impl.FileStorageServiceImpl;
import com.zhentao.mapper.AparticleContentMapper;
import com.zhentao.mapper.ArticleMapper;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.article.pojo.ApArticleContent;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.service.ApArticleContentService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/*
 *云计算
 *魏子纹
 *2025/6/10
 */
@Service
public class ApArticleContentServiceImpl implements ApArticleContentService {
    @Autowired
    private AparticleContentMapper aparticleContentMapper;
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageServiceImpl fileStorageService;

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    @SneakyThrows
    @Async
    public ResponseResult createStaticUrl(Long articleId) {
        //根据id 生成html 静态文件。上传到minio
        QueryWrapper<ApArticleContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = aparticleContentMapper.selectOne(queryWrapper);

        if (apArticleContent!=null){
            // 把内容通过freemarker生产html文件
            Template template = configuration.getTemplate("article.ftl");

            Map<String,Object> map =  new HashMap<>();
            String content = apArticleContent.getContent();
            map.put("content", JSONArray.parseArray(content));

            /*
            *
创建一个 StringWriter 对象 out，用于接收 FreeMarker 模板渲染后的输出内容；
调用 template.process(map, out)，将数据模型 map 填充到模板中，生成最终的 HTML 内容，并写入到 out 中。
            * */
            StringWriter out = new StringWriter();
            template.process(map,out);

            // 把html 上传到 minio
            ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));

            String url = fileStorageService.uploadHtmlFile(apArticleContent.getArticleId() + articleId + ".html", inputStream);

            // 修改ap_article 表里面的 url 字段
            ApArticle apArticle = new ApArticle();
            apArticle.setId(articleId);
            apArticle.setStaticUrl(url);
            articleMapper.updateById(apArticle);

            return ResponseResult.okResult(200,url);

        }



        return ResponseResult.okResult(201,"文章不存在");
    }
}
